package com.wise.wing.activity.order;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.DisplayUtil;
import com.bm.corelibs.utils.ToastMgr;
import com.bm.corelibs.utils.ViewHolder;
import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.nineoldandroids.animation.ObjectAnimator;
import com.squareup.picasso.Picasso;
import com.wise.wing.R;
import com.wise.wing.activity.logic.LoginManager;
import com.wise.wing.activity.logic.OrderManager;
import com.wise.wing.activity.main.BaseActivity;
import com.wise.wing.activity.tools.StringFormattor;
import com.wise.wing.bean.BaseData;
import com.wise.wing.bean.Order;
import com.wise.wing.bean.OrderLog;
import com.wise.wing.constant.Constant;
import com.wise.wing.views.CommonDialog;
import com.wise.wing.views.CommonNavigationBar;
import com.wise.wing.views.CustomDialog;
import com.wise.wing.views.RaitingBarForShowing;
import com.wise.wing.views.SelectCountView;

public class OrderDetailActivity extends BaseActivity implements OnClickListener, OnItemClickListener {

	public static final String ORDER_ID = "ORDER_ID";

	private CommonNavigationBar navi;
	private ListView lv_owners;
	private View header;

	private TextView tv_num, tv_price, tv_cadition_name, tv_time, tv_volume, tv_style, tv_cadition, tv_station_name, tv_contact, tv_remarks, tv_status, tv_action, tv_unitprice, tv_empty;
	private ImageView iv_refresh;
	private LinearLayout ll_empty;
	private Button btn_submit;
	private View divider, bottom_divider;

	private CustomDialog tipsDialog;
	private CommonDialog priceDialog;
	private View priceView;
	private SelectCountView countView;

	private Order order;
	private OwnersAdapter adapter = new OwnersAdapter();
	private OrderManager manager = new OrderManager();

	private Runnable refresh = new Runnable() {
		@Override
		public void run() {
			manager.getOrderDetail(getIntent().getLongExtra(ORDER_ID, 0), getListener());
			mHandler.postDelayed(refresh, Constant.REFRESH_TIME);
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(refresh);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.actitity_order_detail);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		navi = (CommonNavigationBar) findViewById(R.id.navi);
		lv_owners = (ListView) findViewById(R.id.lv_owners);
		btn_submit = (Button) findViewById(R.id.btn_submit);
		divider = (View) findViewById(R.id.divider);
	}

	@Override
	public void init() {
		navi.setTitle(R.string.detail);
		navi.setListener(null);
		initHeader();
		lv_owners.setAdapter(adapter);
		loadingDialog.show();
		System.out.println("ORDER_ID" + getIntent().getLongExtra(ORDER_ID, 0));
		manager.getOrderDetail(getIntent().getLongExtra(ORDER_ID, 0), getListener());
		// manager.getOrderDetail(15, getListener());
		tipsDialog = new CustomDialog(mActivity);
		priceDialog = new CommonDialog(mActivity, "", "", 2);
		mHandler.postDelayed(refresh, Constant.REFRESH_TIME);
	}

	@Override
	public void addListeners() {
		tv_action.setOnClickListener(this);
		btn_submit.setOnClickListener(this);
		lv_owners.setOnItemClickListener(this);
	}

	@SuppressLint("InflateParams")
	private void initHeader() {
		header = LayoutInflater.from(mActivity).inflate(R.layout.layout_order_detail_header, null);
		findHeaderViews();
		lv_owners.addHeaderView(header);
	}

	private void findHeaderViews() {
		tv_num = (TextView) header.findViewById(R.id.tv_num);
		tv_price = (TextView) header.findViewById(R.id.tv_price);
		tv_cadition_name = (TextView) header.findViewById(R.id.tv_cadition_name);
		tv_time = (TextView) header.findViewById(R.id.tv_time);
		tv_volume = (TextView) header.findViewById(R.id.tv_volume);
		tv_style = (TextView) header.findViewById(R.id.tv_style);
		tv_cadition = (TextView) header.findViewById(R.id.tv_cadition);
		tv_station_name = (TextView) header.findViewById(R.id.tv_station_name);
		tv_contact = (TextView) header.findViewById(R.id.tv_contact);
		tv_remarks = (TextView) header.findViewById(R.id.tv_remarks);
		tv_status = (TextView) header.findViewById(R.id.tv_status);
		tv_action = (TextView) header.findViewById(R.id.tv_action);
		tv_empty = (TextView) header.findViewById(R.id.tv_empty);
		ll_empty = (LinearLayout) header.findViewById(R.id.ll_empty);
		bottom_divider = header.findViewById(R.id.bottom_divider);
		tv_unitprice = (TextView) header.findViewById(R.id.tv_unitprice);
		iv_refresh = (ImageView) header.findViewById(R.id.iv_refresh);
	}

	@SuppressLint("SimpleDateFormat")
	private void setHeaderData() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date1 = null;
		Date date2 = new Date(System.currentTimeMillis());
		try {
			date1 = format.parse(order.appointmentTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (order.status != 0 || date1.getTime() - date2.getTime() <= 0) {
			btn_submit.setVisibility(View.GONE);
			int px = DisplayUtil.dip2px(mActivity, 10);
			MarginLayoutParams params = (MarginLayoutParams) divider.getLayoutParams();
			params.setMargins(px, 0, px, px);
			divider.setLayoutParams(params);
		}

		if (order.orderLogs == null || order.orderLogs.size() <= 0) {
			ll_empty.setVisibility(View.VISIBLE);
			if (order.status >= 2 || date1.getTime() - date2.getTime() <= 0) {
				tv_empty.setText("订单已超时，无司机接单");
				if (animator != null)
					animator.cancel();
				// tv_status.setVisibility(View.GONE);
			} else
				tv_empty.setText(R.string.main_hint6);
		} else
			ll_empty.setVisibility(View.GONE);

		if (order.status == 0 || order.status == 1) {
			if (date1.getTime() - date2.getTime() <= 0) {
				tv_action.setVisibility(View.GONE);
			} else {
				tv_action.setVisibility(View.VISIBLE);
			}
		} else {
			tv_action.setVisibility(View.GONE);
		}

		if (order.status == 4) {
			ll_empty.setVisibility(View.GONE);
			if (order.orderLogs == null || order.orderLogs.size() <= 0) {
				bottom_divider.setVisibility(View.GONE);
			} else {
				bottom_divider.setVisibility(View.VISIBLE);
			}
		}

		if (order.status == 6) {
			if (order.orderLogs == null || order.orderLogs.size() <= 0) {
				ll_empty.setVisibility(View.VISIBLE);
				tv_empty.setText("订单已超时，无司机接单");
				if (animator != null)
					animator.cancel();
			} else {
				ll_empty.setVisibility(View.GONE);
			}
			tv_status.setVisibility(View.VISIBLE);
			tv_action.setVisibility(View.GONE);
		}

		tv_num.setText(getResources().getString(R.string.main_hint1) + " " + order.orderNum);
		tv_time.setText(StringFormattor.dropYear(StringFormattor.dropSecond(order.appointmentTime)));
		tv_style.setText(order.style1 + " (" + order.count + "辆)");
		tv_volume.setText(order.volume + "方");
		tv_price.setText("￥" + order.sumPrice);
		tv_status.setText(order.getStatusString(order.status));
		tv_status.setTextColor(order.getStatusTextColor(order.status));
		tv_cadition_name.setText(order.conditionName + ":");
		tv_cadition.setText(order.condition);
		tv_remarks.setText(order.remarks == null || order.remarks.equals("") || order.remarks.equals("null") || order.remarks.length() <= 0 ? "无" : order.remarks);
		tv_station_name.setText(order.stationName);
		// tv_station_add.setText(order.station.addAddress);
		String contact;
		if (order.disName == null || order.disName.length() < 0) {
			contact = order.disPhone;
		} else {
			contact = order.disName + " (" + order.disPhone + ")";
		}
		tv_contact.setText(contact);
		tv_unitprice.setText(new java.text.DecimalFormat("0.00").format((order.sumPrice / order.volume)) + "元/方");

		if (animator == null) {
			animator = ObjectAnimator.ofFloat(iv_refresh, "rotation", 0, 359);
			animator.setDuration(1000);
			animator.setRepeatMode(ObjectAnimator.RESTART);
			animator.setRepeatCount(ObjectAnimator.INFINITE);
			animator.start();
		}
	}

	ObjectAnimator animator;

	private NListener<BaseData> getListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					if (data.data.disOrderDetail != null) {
						order = data.data.disOrderDetail;
						for (int i = order.orderLogs.size() - 1; i >= 0; i--) {
							if (order.orderLogs.get(i).statusId == 16)
								order.orderLogs.remove(i);
						}
						setHeaderData();
						adapter.notifyDataSetChanged();
					}
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
				loadingDialog.dismiss();
			}
		};
	}

	class OwnersAdapter extends BaseAdapter implements OnClickListener {

		@Override
		public int getCount() {
			return order == null || order.orderLogs == null ? 0 : order.orderLogs.size();
		}

		@Override
		public Object getItem(int position) {
			return order.orderLogs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_order_owners, null);

			OrderLog ol = (OrderLog) getItem(position);

			TextView tv_name = ViewHolder.get(convertView, R.id.tv_name);
			TextView tv_licenseplateNum = ViewHolder.get(convertView, R.id.tv_licenseplateNum);
			TextView tv_style = ViewHolder.get(convertView, R.id.tv_style);
			TextView tv_owner_status = ViewHolder.get(convertView, R.id.tv_owner_status);
			ImageView iv_icon = ViewHolder.get(convertView, R.id.iv_icon);
			LinearLayout ll_bg = ViewHolder.get(convertView, R.id.ll_bg);
			ImageView iv_cancel = ViewHolder.get(convertView, R.id.iv_cancel);
			ImageView iv_change = ViewHolder.get(convertView, R.id.iv_change);
			ImageView iv_tel = ViewHolder.get(convertView, R.id.iv_tel);
			RaitingBarForShowing ratingbar = ViewHolder.get(convertView, R.id.ratingbar);

			iv_tel.setOnClickListener(this);
			iv_tel.setTag(ol.phone);
			tv_name.setText(ol.driver);
			ratingbar.setRate(ol.averageScore);
			tv_licenseplateNum.setText(ol.licensePlate + ol.licensePlateNum);
			tv_style.setText(ol.style1 + ":" + ol.styleName);
			Picasso.with(mActivity).load(ol.icon).resize(720, 720).centerCrop().transform(new RoundedTransformationBuilder().oval(true).build()).into(iv_icon);

			if (order.status == 2 || order.status == 3 || order.status == 0 || order.status == 1 || order.status == 6) {
				tv_owner_status.setVisibility(View.VISIBLE);
				if (ol.damage <= 0)
					tv_owner_status.setText(ol.getStatusMsg(ol.statusId));
				else
					tv_owner_status.setText(ol.getStatusMsg(ol.statusId) + "(获赔" + ol.damage + "元)");
			} else if (order.status == 4) {
				if (ol.statusId == 5 || ol.statusId == 11 || ol.statusId == 12) {
					tv_owner_status.setVisibility(View.INVISIBLE);
				} else {
					tv_owner_status.setVisibility(View.VISIBLE);
					tv_owner_status.setText("获赔" + ol.damage + "元");
				}
			} else {
				tv_owner_status.setVisibility(View.INVISIBLE);
			}

			if (order.status == 4) {
				ll_bg.setBackgroundColor(mActivity.getResources().getColor(R.color.gray));
				iv_tel.setVisibility(View.GONE);
			} else {
				if (ol.statusId == 5 || ol.statusId == 11 || ol.statusId == 12 || ol.statusId == 13 || ol.statusId == 14) {
					ll_bg.setBackgroundColor(mActivity.getResources().getColor(R.color.gray));
				} else {
					ll_bg.setBackgroundColor(mActivity.getResources().getColor(R.color.main));
				}
				iv_tel.setVisibility(View.VISIBLE);
			}

			if (ol.statusId == 5) {
				iv_cancel.setVisibility(View.VISIBLE);
			} else {
				iv_cancel.setVisibility(View.GONE);
			}

			if (ol.statusId == 3) {
				iv_change.setVisibility(View.VISIBLE);
			} else {
				iv_change.setVisibility(View.GONE);
			}

			return convertView;
		}

		@Override
		public void onClick(View v) {
			String tel = (String) v.getTag();
			Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
			startActivity(callIntent);
		}
	}

	@SuppressLint("InflateParams")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_action:
			if (order.orderLogs.size() <= 0) {
				tipsDialog = new CustomDialog(mActivity);
				tipsDialog.show();
				OnClickListener listener = new OnClickListener() {
					@Override
					public void onClick(View v) {
						tipsDialog.dismiss();
						loadingDialog.show();
						manager.cancelOrder(LoginManager.getInstance(mActivity).getId(), order.id, order.orderNum, order.sumPrice, getCancelListener());
					}
				};
				tipsDialog.justShowMsg(R.string.detail_hint6, listener);
			} else {
				loadingDialog.show();
				manager.getDamage(order.id, new NListener<BaseData>() {
					@Override
					public void onResponse(BaseData data) {
						loadingDialog.dismiss();
						if(data.status == Constant.STATUS_OK) {
							tipsDialog = new CustomDialog(mActivity);
							tipsDialog.show();
							OnClickListener listener = new OnClickListener() {
								@Override
								public void onClick(View v) {
									tipsDialog.dismiss();
									loadingDialog.show();
									manager.cancelOrder(LoginManager.getInstance(mActivity).getId(), order.id, order.orderNum, order.sumPrice, getCancelListener());
								}
							};
							tipsDialog.justShowMsg("当前时间距离用车时间还有" + data.data.hourdff + ", 撤销订单将会扣除" + data.data.fine + "元罚金", listener);
						}
					}

					@Override
					public void onErrResponse(VolleyError error) {
						loadingDialog.show();
					}

					@Override
					public void onAllPageLoaded(int nowPage, int totalPage) {}
				});
			}

			break;

		case R.id.btn_submit:
			if (priceView == null) {
				priceView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_add_price, null);
				countView = (SelectCountView) priceView.findViewById(R.id.sc_addprice);
			}
			countView.setCount(order.changeUnitPrice);
			priceDialog.show();
			priceDialog.setCustomView(priceView);
			priceDialog.hideTitle();
			priceDialog.setPositiveListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					priceDialog.dismiss();
					if (countView.getCount() < 0)
						return;
					tipsDialog = new CustomDialog(mActivity);
					tipsDialog.show();
					OnClickListener okListener = new OnClickListener() {
						@Override
						public void onClick(View v) {
							tipsDialog.dismiss();
							loadingDialog.show();
							manager.increateOrderPrice(order.id, countView.getCount(), increaseListener());
						}
					};
					OnClickListener cancelListener = new OnClickListener() {
						@Override
						public void onClick(View v) {
							tipsDialog.dismiss();
							priceDialog.show();
						}
					};
					if (order.changeUnitPrice > countView.getCount())
						tipsDialog.justShowMsg("单价调整为" + (order.unitPrice + countView.getCount()) + "元，订单总额减少" + ((order.changeUnitPrice - countView.getCount()) * order.volume) + "元", okListener, cancelListener);
					else
						tipsDialog.justShowMsg("单价调整为" + (order.unitPrice + countView.getCount()) + "元，订单总额增加" + (countView.getCount() * order.volume) + "元", okListener, cancelListener);
				}
			});
			break;
		}
	}

	private NListener<BaseData> increaseListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					countView.setCount(0);
					loadingDialog.show();
					manager.getOrderDetail(order.id, getListener());
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}

	private NListener<BaseData> getCancelListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					manager.getOrderDetail(order.id, getListener());
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position == 0)
			return;
		if (order.status != 4) {
			OrderLog orderLog = (OrderLog) parent.getAdapter().getItem(position);
			Intent intent = new Intent(mActivity, OwnerDetailActivity.class);
			intent.putExtra(OwnerDetailActivity.OWNER, orderLog);
			intent.putExtra(OwnerDetailActivity.ORDER, order);
			startActivityForResult(intent, 1);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resonseCode, Intent data) {
		if (resonseCode == RESULT_OK) {
			loadingDialog.show();
			manager.getOrderDetail(getIntent().getLongExtra(ORDER_ID, 0), getListener());
		}
	}

}
